<?php

class Service_Static {

	const SECOND_VI = 'giây';
	const MINUTE_VI = 'phút';
	const HOUR_VI = 'giờ';
	const DAY_VI = 'ngày';
	const WEEK_VI = 'tuần';
	const MONTH_VI = 'tháng';
	const YEAR_VI = 'năm';
	const DECADE_VI = 'thập kỷ';
	const AGO_VI = 'trước';
	const NOW_VI = 'hiện tại';

	/**
	 *
	 * @return string
	 */
	public static function get_base_url() {
		return Kohana::$config->load('site')->domain . '/';
	}

	public static function get_current_url() {
		$page_url = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
		if ($_SERVER["SERVER_PORT"] != "80") {
			$page_url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
		} else {
			$page_url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
		}

		return $page_url;
	}

	/**
	 * timeAgo
	 *
	 * Function for Facebook like times: '3 weeks ago'
	 *
	 * Note: The separate array with plurals is for multilingual purposes (eg. in Dutch it's 'minuut' and 'minuten').
	 *
	 * @param integer $timestamp
	 * @return string
	 */
	public static function show_date_formated($timestamp) {
		// Configuration
		$singular = array(self::SECOND_VI, self::MINUTE_VI, self::HOUR_VI, self::DAY_VI, self::WEEK_VI, self::MONTH_VI, self::YEAR_VI, self::DECADE_VI);
		$plural = array(self::SECOND_VI, self::MINUTE_VI, self::HOUR_VI, self::DAY_VI, self::WEEK_VI, self::MONTH_VI, self::YEAR_VI, self::DECADE_VI);
		$suffix = self::AGO_VI;
		$now = self::NOW_VI;

		// Prepare
		$time = time();
		$difference = $time - $timestamp;
		$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);

		$amount = 0;
		// Calculate lowest dividable amount
		for ($i = 7; $i >= 0 && ($amount = $difference / $lengths[$i]) <= 1; --$i)
			;

		// Now or in the future
		if ($amount <= 0)
			return $now;

		// Return as string
		$amount = floor($amount);
		if ($i < 0) {
			$i = 0;
		}
		return $amount . ' ' . ($amount > 1 ? $plural[$i] : $singular[$i]) . ' ' . $suffix;
	}

//	public static function show_date_formated($date) { // $date -->  time(); value
//		$stf = 0;
//		$cur_time = time();
//		$diff = $cur_time - $date;
//		$phrase = array(self::SECOND_VI, self::MINUTE_VI, self::HOUR_VI, self::DAY_VI, self::DAY_VI, self::MONTH_VI, self::YEAR_VI, self::YEAR_VI);
//		$length = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
//		for ($i = sizeof($length) - 1; ($i >= 0) && (($no = $diff / $length[$i]) <= 1); $i--) {
////			;
//			if ($i < 0)
//				$i = 0;
//			$_time = $cur_time - ($diff % $length[$i]);
//			$no = floor($no);
//			if ($no <> 1)
//				$phrase[$i] .= 's';
//			$value = sprintf("%d %s ", $no, $phrase[$i]);
//			if (($stf == 1) && ($i >= 1) && (($cur_time - $_time) > 0))
//				$value .= time_ago($_time);
//		}
//
////		return $value.' ago ';
//		return sprintf("%s %s ", $value, self::AGO_VI);
//	}

	public static function remove_non_utf8_char($string) {
		//reject overly long 2 byte sequences, as well as characters above U+10000 and replace with ?
		$string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]' .
				'|[\x00-\x7F][\x80-\xBF]+' .
				'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*' .
				'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})' .
				'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S', '?', $string);

		//reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
		$string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]' .
				'|\xED[\xA0-\xBF][\x80-\xBF]/S', '?', $string);

		return $string;
	}

	public static function format_description($description) {
		if (strlen($description) > 1) {
			$expolded = explode("\n", $description);
			$description_formated = '';
			foreach ($expolded as $part) {
				$description_formated .= "<p>{$part}</p>";
			}
			$description = $description_formated;
		}

//		$description = self::replace_link_by_tag($description);
		$description = self::remove_non_utf8_char($description);
		return trim($description);
	}

	public static function replace_link_by_tag($html) {
		if (strlen($html) == 0) {
			return '';
		}
		try {
			$dom = new DOMDocument;
			$dom->loadHTML($html);
			$xPath = new DOMXPath($dom);
			$texts = $xPath->query(
					'/html/body//text()[
        not(ancestor::a) and (
        contains(.,"http://") or
        contains(.,"https://") or
        contains(.,"ftp://") )]'
			);
			foreach ($texts as $text) {
				$fragment = $dom->createDocumentFragment();
				$fragment->appendXML(
						preg_replace(
								"~((?:http|https|ftp)://(?:\S*?\.\S*?))(?=\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)~i", '<a href="$1">$1</a>', $text->data
						)
				);
				$text->parentNode->replaceChild($fragment, $text);
			}

			return $dom->saveXML($dom->documentElement);
		} catch (Exception $e) {
			return $html;
		}
	}

	public static function strip_tags($str) {
		$allowable_tags = '<p><a>';

		return strip_tags($str, $allowable_tags);
	}

	/**
	 *
	 * @return string
	 */
	public static function get_ip_address() {
		if (isset($_SERVER["REMOTE_ADDR"])) {
			$ip = $_SERVER["REMOTE_ADDR"];
		} else if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
			$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
			$ip = $_SERVER["HTTP_CLIENT_IP"];
		}

		return $ip;
	}

}
